/*
 * adc.c
 *
 *  Created on: 2015-03-08
 *      Author: atreyu
 */

#include "adc.h"

void initADC0(void)
{
	sequence = 0;
	int retCode=0;
	adcReady = 0;
	adcReadCount=0;

	bt_UARTsend("Init ADC");
	loading_bar(27);
	load_okfail(1);

	ROM_SysCtlADCSpeedSet(SYSCTL_ADCSPEED_250KSPS);
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_ADC0);
	ROM_ADCHardwareOversampleConfigure(ADC0_BASE, 64);
	ROM_GPIOPinTypeADC(GPIO_PORTE_BASE, _ADC);


	ROM_ADCSequenceDisable(ADC0_BASE, sequence);


	ROM_ADCSequenceConfigure(ADC0_BASE, sequence, ADC_TRIGGER_TIMER, 0);

	ROM_ADCSequenceStepConfigure(ADC0_BASE, sequence, 0, ADC_CTL_CH3 | ADC_CTL_IE |
                             ADC_CTL_END);


	ROM_ADCIntEnable(ADC0_BASE, sequence);
	ROM_IntEnable(INT_ADC0SS0);


	ROM_ADCSequenceEnable(ADC0_BASE, sequence);


	ROM_ADCIntClear(ADC0_BASE, sequence);

	//bt_UARTsend("Init ADC...end\r\n");

	//init buffers for adc and each object
	//retCode=init_cBuffer(&adc, 5000, 4);
	//NODE *adc;
	//retCode = node_init(&adcBuf);
	adccount = 0;
	retCode = init_array(adcArr);
	if(retCode)
	{
		bt_UARTsend("Init ADC Buffer");
		loading_bar(20);
		load_okfail(1);
	}
	else
	{
		bt_UARTsend("Init ADC Buffer");
		loading_bar(20);
		load_okfail(0);
	}
	//cBuffer_free(&adc);

}

void adc0inthandler(void)
{
	int temp=0;
	//int temp0,temp1,temp2,temp3;
	// Read ADC Value.
	ROM_ADCSequenceDataGet(ADC0_BASE, sequence, ulADC0_Value);
	gADCvalue=ulADC0_Value[0];

	//adc_digi = 3.3*(ulADC0_Value[0])/4095;

	//currently this is a little messy, it should be looking for a hi to lo transition
	//then starting the push, pop ops. Then on a lo to hi transition
	//it should normalize the array and send that to the stepper queue
	//if(pollC[1][0]) cBuffer_push_end(&adc, ulADC0_Value);

	if(adcReady && gBeltRunning)
	{
		push_array(gADCvalue, adcArr);
		adcReadCount++;
	}


	ROM_ADCIntClear(ADC0_BASE, sequence);
}

void printReadCount()
{
	bt_UARTsend("\t\t\t\tadcReadCount: ");
	bt_UARTsend(itoa(adcReadCount,10));
	bt_UARTsend("\r\n");
}

